package com.java.base.exercise.jvm;

import com.java.base.exercise.People;
import com.java.base.exercise.util.UnsafeInstance;
import org.openjdk.jol.info.ClassLayout;
import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @Author RenPu
 * @Date 2022/5/8 13:42
 * @Version 1.0
 * @Description: 使用openJdk依赖，打印出对象的空间布局
 **/
public class JolTest {

          private static final long initnalSize =8;
          private static final long oneHundred=1193123491341341234L;
          private static final Unsafe reflectInstance = UnsafeInstance.getReflectInstance();



    public static void main(String[] args) {


        //调用方法分配堆外内存大小
        long initMemory = reflectInstance.allocateMemory(initnalSize);
        if(initMemory>0){

            //将数据存放在堆外内存
            reflectInstance.putAddress(initMemory,oneHundred);
        }

        //从堆外内存获取数据
        long value = reflectInstance.getAddress(initMemory);

        System.out.println("从对外内存获取值为：---、、、、、、OUT HEAP MEMORY、、、、、、、"+value);

        //释放堆外内存空间资源
        reflectInstance.freeMemory(initMemory);


        //通过cas方法，更改对象属性为非基本类型的方式
        AtomicReferenceFieldUpdater<People, Integer> referenceFieldUpdater = AtomicReferenceFieldUpdater.newUpdater(People.class, Integer.class, "age");

        //通过cas方法，更改对象属性为基本类型的方式
        AtomicIntegerFieldUpdater<People> fieldUpdater = AtomicIntegerFieldUpdater.newUpdater(People.class, "sex");
        People people = new People();
        people.setSex(10);
        people.setAge(59);
        people.setName("你你你你");
        fieldUpdater.getAndIncrement(people);
        referenceFieldUpdater.getAndSet(people,1);
        System.out.println("通过CAS方法进行修改过后：&&&&&&&&&&&&&性别SEX&&&&&&&&&&&"+people.getSex());

        System.out.println("通过CAS方法进行修改过后：===========年龄AGE========"+people.getAge());


        System.out.println(ClassLayout.parseInstance(people).toPrintable());
    }
}
